package com.dd.cloud.user.service.doctor.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.BigDecimalUtils;
import com.dd.cloud.common.utils.DateUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.chknowl.ChknowlChVideo;
import com.dd.cloud.user.entity.chknowl.ChnowlVideoRecord;
import com.dd.cloud.user.entity.doctor.DoctorStudyRecord;
import com.dd.cloud.user.mapper.doctor.DoctorStudyRecordMapper;
import com.dd.cloud.user.req.doctor.DoctorStudyReq;
import com.dd.cloud.user.service.chknowl.IChknowlChVideoService;
import com.dd.cloud.user.service.chknowl.IChnowlVideoRecordService;
import com.dd.cloud.user.service.doctor.IDoctorStudyRecordService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 医生学习记录表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2024-02-21
 */
@Service
public class DoctorStudyRecordServiceImpl extends ServiceImpl<DoctorStudyRecordMapper, DoctorStudyRecord> implements IDoctorStudyRecordService {

    @Autowired
    private IChknowlChVideoService chknowlChVideoService;

    @Autowired
    private IChnowlVideoRecordService chnowlVideoRecordService;

    @Autowired
    private DoctorStudyRecordMapper doctorStudyRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStudyRecord(Integer studyId,
                               Integer type,
                               BigDecimal rate,
                               String name,
                               String img,
                               Integer chapter,
                               Integer doctorId) {
        DoctorStudyRecord doctorStudyRecord = new DoctorStudyRecord();
        //视频观看记录重新计算
        if (type == 1) {
            ChknowlChVideo chknowlChVideo = chknowlChVideoService.getById(studyId);
            Integer totalTime = chknowlChVideo.getTotalTime();
            LambdaQueryWrapper<ChnowlVideoRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ChnowlVideoRecord::getDoctorId,doctorId)
                    .eq(ChnowlVideoRecord::getVideoId, studyId)
                    .eq(ChnowlVideoRecord::getStatus, 1);
            List<ChnowlVideoRecord> list = chnowlVideoRecordService.list(queryWrapper);
            Integer sum = 0;
            if (CollectionUtils.isNotEmpty(list)) {
                for (ChnowlVideoRecord chnowlVideoRecord : list) {
                    sum += Integer.valueOf(chnowlVideoRecord.getTime());
                }
            }
            rate = BigDecimalUtils.divide(sum,totalTime).multiply(new BigDecimal(100));
        }

        DoctorStudyRecord record = doctorStudyRecordMapper.queryDoctorStudentRecord(doctorId, type, LocalDate.now(), studyId);
        if (record == null) {
            doctorStudyRecord.setDoctorId(doctorId)
                    .setStudyId(studyId)
                    .setRate(rate)
                    .setName(name)
                    .setCreateDate(LocalDateTime.now())
                    .setStatus(1)
                    .setImg(img)
                    .setChapter(chapter)
                    .setType(type);
            Boolean flag = this.save(doctorStudyRecord);
            if (!flag) {
                throw new ZekeException("保存失败");
            }
        } else {
            record.setDoctorId(doctorId)
                    .setStudyId(studyId)
                    .setRate(rate)
                    .setName(name)
                    .setCreateDate(LocalDateTime.now())
                    .setStatus(1)
                    .setImg(img)
                    .setChapter(chapter)
                    .setType(type);
            Boolean flag = this.updateById(record);
            if (!flag) {
                throw new ZekeException("更新失败");
            }
        }
    }

    @Override
    public Page<DoctorStudyRecord> queryDoctorStudyPage(DoctorStudyReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        LambdaQueryWrapper<DoctorStudyRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (req.getType() != null) {
            queryWrapper.eq(DoctorStudyRecord::getType, req.getType());
        }
        String halfYear = DateUtils.pastHalfYear("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(halfYear);
        LocalDate endDate = LocalDate.now();
        req.setStartDate(startDate);
        req.setEndDate(endDate);
        req.setDoctorId(loginInfo.getId());
        Page<DoctorStudyRecord> page = req.pagePojo();
        page = this.getBaseMapper().queryDoctorStudyPage(page, req);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStudyStatus(String studyIds) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        String[] ids = studyIds.split(",");
        List<Integer> studyList = new ArrayList<>();
        for (String id : ids) {
            studyList.add(Integer.parseInt(id));
        }
        LambdaUpdateWrapper<DoctorStudyRecord> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(DoctorStudyRecord::getStudyId, studyList)
                .eq(DoctorStudyRecord::getDoctorId, loginInfo.getId())
                .set(DoctorStudyRecord::getStatus, -1);
        Boolean flag = this.update(updateWrapper);
        if (!flag) {
            throw new ZekeException("删除失败");
        }
    }
}
